<template>
  <div class="questionEdit">
    <el-form :rules="{}" ref="ruleFormRef" :model="dataRequest" label-width="120px">
      <div class="flex-jc-s-b" style="margin-bottom: 13px">
        <div class="left-title">内容</div>
      </div>
      <div class="flex-center">
        <!-- <span style="margin: 0 15px 0 70px">内容</span> -->
        <div style="" class="flex-center">
          <span v-html="dataRequest.content"></span>
          <el-button type="primary" @click="editQuestions(dataRequest.content, 'content')" :text="true">
            编辑</el-button>
        </div>
      </div>
      <div v-if="dataRequest.typeCode != 'case'">
        <div class="left-title" style="margin: 10px 0">答案选项</div>
        <div class="flex-center" v-for="(item, index) in dataRequest.optionList">
          <span style="margin: 0 15px 0 70px">{{ "选项" + item.option }}</span>
          <div style="" class="flex-center">
            <span v-html="item.content"></span>
            <el-button type="primary" @click="editQuestions(item, index)" :text="true">
              编辑</el-button>
          </div>
        </div>
        <el-form-item :label="'正确答案'" style="align-items: center">
          <!-- v-if="dataRequest.typeCode!='fillBlank'&&dataRequest.typeCode!='shortAnswer'" -->
          <div style="width: 90%" v-if="dataRequest.typeCode != 'fillBlank' &&
            dataRequest.typeCode != 'shortAnswer'
            ">
            <el-checkbox-group v-model="dataRequest.answer" v-if="dataRequest.typeCode == 'multiple'">
              <el-checkbox v-for="(item, index) in dataRequest.optionList" :label="item.option" size="large">{{
                item.option }}
              </el-checkbox>
            </el-checkbox-group>
            <el-radio-group v-else v-model="dataRequest.answer">
              <el-radio v-for="(item, index) in dataRequest.optionList" :label="item.option" size="large">{{ item.option
              }}</el-radio>
            </el-radio-group>
          </div>
          <!-- 简答题和填空题 -->
          <div style="width: 90%" v-else>
            <div style="" class="flex-center">
              <span v-html="dataRequest.answer"></span>
              <el-button type="primary" @click="editQuestions(dataRequest.answer, 'answer')" :text="true">
                编辑</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="'试题解析'" style="transform: translateY(-30px)">
          <div style="" class="flex-center">
            <span v-html="dataRequest.analysisContent"></span>
            <el-button type="primary" @click="
              editQuestions(dataRequest.analysisContent, 'analysisContent')
              " :text="true">
              编辑</el-button>
          </div>
        </el-form-item>
        <!--  -->
      </div>
    </el-form>
    <!-- :before-close="handleClose" -->
    <el-dialog :title="editTitle" v-model="dialogVisible" @close="closeDialog">
      <div style="padding-bottom: 15px">
        <div style="width: 100%; height: 300px">
          <Toolbar style="border-bottom: 1px solid #ccc; height: 30%" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="'default'" />
          <Editor style="overflow-y: hidden; height: 69%" v-model="valueHtml" :defaultConfig="editorConfig"
            :mode="'default'" @onCreated="handleCreated" />
        </div>
      </div>
      <template #footer>
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirmHtml">确 定</el-button>
      </template>
    </el-dialog>
    <div style="
        position: absolute;
        bottom: 15px;
        width: 152px;
        left: 50%;
        margin-left: -76px;
      " class="flex-jc-s-b">
      <el-button style="margin: 0" type="default" @click="backEdit('', 'edit')">返 回</el-button>
      <el-button style="margin: 0" @click="saveEdit" type="primary" size="small">保 存</el-button>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { QuillEditor, Quill } from "@vueup/vue-quill";
import {
  editDetailApi,
  questionDetailApi,
} from "../allQuestion/detailsQuestion/const.js";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { Boot } from "@wangeditor/editor";
import attachmentModule from "@wangeditor/plugin-upload-attachment";
import "@wangeditor/editor/dist/css/style.css";
import { uploadOssApi } from "@/api/public";
// Quill.register(quillTool, true)
// Quill.register('modules/ImageExtend', ImageExtend)
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { useRouter, useRoute } from "vue-router";
import { getToken } from "@/utils/auth";
if (Boot.plugins.length < 13) {
  //判断如果已经插入进去，不在二次插入
  Boot.registerModule(attachmentModule);
}
const ossData = reactive({
  policy: "",
  signature: "",
  key: "",
  ossaccessKeyId: "",
  dir: "",
  host: "",
});
const actionUrl = ref("");
const editorRef = shallowRef();
const valueHtml = ref("");
const editKey = ref("");
const editTitle = ref("内容编辑");
const dialogVisible = ref(false);
const toolbarConfig = {
  insertKeys: {
    index: 22, // 自定义插入的位置
    keys: ["uploadAttachment"], // “上传附件”菜单
  },
};
const editorConfig = {
  placeholder: "请输入内容...",
  withCredentials: false,
  autofocus: true,
  MENU_CONF: {
    uploadImage: {
      customUpload(file, insertFn) {
        uploadOssApi(file, (url) => {
          insertFn(url);
        });
      },
    },
    uploadVideo: {
      customUpload(file, insertFn) {
        uploadOssApi(file, (url) => {
          insertFn(url);
        });
      },
    },
    uploadAttachment: {
      title: "上传附件",
      fieldName: "fileList",
      customUpload(file, insertFn) {
        uploadOssApi(file, (url) => {
          insertFn(file.name, url);
        });
      },
    },
  },
};
const route = useRoute();
const router = useRouter();
const props = defineProps({
  scope: { default: "" },
  routeType: { default: "pages" },
});
const content = ref("");
const dataRequest = reactive({
  id: null,
  content: "",
  typeCode: "single",
  optionList: [],
  answer: "A",
  analysisContent: "",
});
const editorOption = reactive({
  ImageExtend: {
    name: "file_name", // 参数名
    action: "/backend/upload/image", // 服务器地址，如果为空则采用base64插入图片
    headers: (xhr) => {
      // 设置请求头参数（选填）
      xhr.setRequestHeader("s", "疯狂星期四v50");
    },
    response: (res) => {
      return res.data.url;
    },
    size: 8, // 图片不能超过8M
    sizeError: () => {
      ElMessage.error("粘贴图片大小不能超过8MB!");
    },
  },
  modules: {
    toolbar: {
      container: [
        [{ size: ["small", false, "large", "huge"] }], // 字体大小
        ["bold", "italic", "underline", "link"], // 加粗 斜体 下划线 删除线,链接
        [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
        ["clean", "image"], // 清除文本格式,图片
      ],
    },
  },
  toolbar: {},
});
onMounted(() => {
  initDetail();
});
function getUUID() {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    return (c === "x" ? (Math.random() * 16) | 0 : "r&0x3" | "0x8").toString(
      16
    );
  });
}
const confirmHtml = () => {
  if (
    editKey.value == "content" ||
    editKey.value == "answer" ||
    editKey.value == "analysisContent"
  ) {
    dataRequest[editKey.value] = JSON.parse(JSON.stringify(valueHtml.value));
  } else {
    dataRequest["optionList"][editKey.value].content = JSON.parse(JSON.stringify(valueHtml.value));
  }
  closeDialog();
};
const closeDialog = () => {
  dialogVisible.value = false;
  // console.log(dialogVisible.value, 'dialogVisible.value')
};
const editQuestions = (item, key) => {
  editKey.value = key;
  switch (key) {
    case "content":
      editTitle.value = "内容编辑";
      valueHtml.value = `<p>${item}</p>`;
      break;
    case "answer":
      editTitle.value = "答案编辑";
      valueHtml.value = `<p>${item}</p>`;
      break;
    case "analysisContent":
      editTitle.value = "试题解析编辑";
      valueHtml.value = `<p>${item}</p>`;
      break;
    default:
      editTitle.value = "选项" + item.option;
      valueHtml.value = `<p>${item.content}</p>`;
      break;
  }
  dialogVisible.value = true;
};
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const emit = defineEmits(["backEdit"]);
const initDetail = () => {
  questionDetailApi(route.query.id).then((res) => {
    for (const key in dataRequest) {
      dataRequest[key] = res.data[key] || "";
    }
    // 默认多选框
    if (res.data.typeCode == "multiple") {
      dataRequest.answer = [];
      res.data.answer.split("").map((item) => {
        dataRequest.answer.push(item);
      });
    }
  });
};
const backEdit = () => {
  console.log(props.routeType, "props.routeType");
  emit("backEdit", { id: route.query.id }, route.query.back);
};
const saveEdit = () => {
  let remOptionList = [];
  console.log(dataRequest, "dataRequest");
  dataRequest.optionList.map((item) => {
    !item.content ? remOptionList.push(item) : "";
  });
  if (!dataRequest.content) {
    ElMessage.warning("请输入题目内容");
    return;
  }
  if (remOptionList.length > 0) {
    ElMessage.warning("请输入答案选项");
    return;
  }
  let answer = "";
  if (dataRequest.typeCode == "multiple") {
    if (dataRequest.answer.length == 0) {
      ElMessage.warning("请选择多选题答案");
      return;
    }
    dataRequest.answer.map((item) => {
      answer = answer + item;
    });
  } else {
    answer = dataRequest.answer;
  }
  editDetailApi({
    answer,
    content: dataRequest.content,
    id: dataRequest.id,
    optionList: dataRequest.optionList,
    analysisContent: dataRequest["analysisContent"],
  }).then((res) => {
    ElMessage.success(res.msg || "操作成功");
    emit("backEdit", { id: route.query.id }, route.query.back, "finishEdit");
  });
};
// 除去富文本
function removeTag(str, len) {
  // str = str.replace(/<\/?[^>]*>/g, '');       //匹配所有html标签
  // str = str.replace(/<p[^>]*>/g, '<p class="tag-class">'); //去除标签内所有属性，并设置自定义类名
  // str = str.replace(/(\n)/g, '')             //去除换行
  // str = str.replace(/\s+style="[^"]*"/g, '') //去除style样式
  // str = str.replace(/&nbsp;/gi, '')          //去除空格
  // str = str.replace(/\<img/gi, '<img class="img_class"');  //添加自定义样式
  return str;
}
</script>
<style lang="scss">
.questionEdit {
  .el-form-item {
    align-items: center;
  }
}
</style>
<style lang="scss" scoped>
.flex-center {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
}
</style>
